import { defineStore } from "pinia";
import { ref } from "vue";

export const useSearchStore = defineStore(
  "useSearchStore",
  () => {
    const searchList = ref<string[]>([]);

    function getSearchHistory() {
      return searchList.value;
    }

    //添加历史搜索记录
    function addSearch(str: string) {
      const index = searchList.value.indexOf(str);
      console.log(index);
      //判断是否已经用
      if (index !== -1) {
        //有就删除
        searchList.value.splice(index, 1);
      }
      //添加历史记录，保持置顶
      searchList.value.unshift(str);
    }

    //删除历史搜索记录
    function delSearch(str: string) {
      const index = searchList.value.indexOf(str);
      searchList.value.splice(index, 1);
    }

    //删除所有历史记录
    function delAllSearch() {
      searchList.value = [];
    }

    return {
      searchList,
      getSearchHistory,
      addSearch,
      delSearch,
      delAllSearch,
    };
  },

  {
    //开启持久化
    persist: {
      key: "yx:shopping:search",
    },
  }
);
